import { Param } from "../models";
const getParam = (params: Param[], name: string): Param => {
    for (const i in params) {
        if (params[i].name === name) {
            return params[i]
        }
    }
    throw Error("Get param failed")
}

export const formatterTransferFunction = (params: Param[]): string => {
    const num = (getParam(params, 'num').value as number[][])[0]
    const den = (getParam(params, 'den').value as number[][])[0]

    const formatStr = (num: number[]): string => {
        let numStr = ""
        for (let i = 0; i < num.length; i++) {
            const numValue = num[i] // 当前位置分子的值
            const powerNumber = num.length - i - 1 // 乘方
            const sValue = powerNumber > 1 ? `s^{${powerNumber}}` : powerNumber > 0 ? "s" : ""
            if (numValue > 0) {
                if (numStr != "") {
                    numStr = numStr + '+'
                }
                if (numValue !== 1 || (numValue == 1 && sValue == "")) {
                    numStr = numStr + numValue
                }
                numStr += sValue
            } else if (numValue < 0) {
                if (numValue !== -1 || (numValue == -1 && sValue == "")) {
                    numStr = numStr + numValue
                } else {
                    numStr = numStr + "-"
                }
                numStr += sValue
            }
        }
        return numStr
    }
    return `\\frac{${formatStr(num)}}{${formatStr(den)}}`
}



const formatters: { [key: string]: (params: Param[]) => string } = {
    transferfunction: formatterTransferFunction
}

export const specialFormat = (type: string, params: Param[]): string => {
    const formatter = formatters[type.toLowerCase()]
    if (formatter == null) {
        throw Error(`Formatter error in type ${type}`)
    }
    return formatter(params)
}